/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
    Component,
    PropTypes
} from 'react';

import {
  View,
  StyleSheet,
  Text,
  StatusBar,
  Navigator,
  BackAndroid,
  Alert,
  ToastAndroid,
  Platform,
  NetInfo
} from 'react-native';

import {Scene, Reducer, Router, TabBar, Modal, Actions, ActionConst } from 'react-native-router-flux';

import { connect } from 'react-redux';
import Ionicons  from 'react-native-vector-icons/Ionicons';
import AppConfig from '../config.js';
import CommonStyles from '../styles/common';
import Colors from '../styles/colors';
import {ChangeNetInfo,ChangeNetExpensiveStatus,ChangeNetConnectStatus} from '../actions/netInfo';

import TabIcon from '../components/tabIcon';
import MainContainer from './main';
import LoginContainer from './login';
import UserCenterContainer from './userCenter';
import ScanContainer from './scan';
import TakePhoto from '../pages/takePhoto';
import ImageUpload from '../pages/imageUpload';

import {SceneFocus} from '../actions/routes';

class App extends Component {      
  constructor(props) {
    super(props);
    this.state={
        backButtonImage:null,
        rightBtnScanImage:null,
    };
    this.backAndroidHandler = this.backAndroidHandler.bind(this);
  }
  
  reducerCreate(params) {
    const defaultReducer = Reducer(params);
    return (state, action) => {
        if(action.type==ActionConst.FOCUS){
            this.props.dispatch(SceneFocus(action.scene));
        }
        return defaultReducer(state, action);
    };
  }  
  
  componentWillMount(){
      NetInfo.addEventListener('change',this.handleConnectionInfoChange.bind(this));
      NetInfo.isConnected.addEventListener('change',this.handleConnectivityChange.bind(this));
      //获取网络当前信息
      NetInfo.fetch().done((connectionInfo) => {
          var info=this.switchConnectionInfo(connectionInfo);
          this.props.dispatch(ChangeNetInfo(info));
      });
      //获取网络当前连接状态
      NetInfo.isConnected.fetch().then((isConnected) => {
          this.props.dispatch(ChangeNetConnectStatus(isConnected));
      });
      //获取网络当前连接计费状态
      NetInfo.isConnectionExpensive().then((isConnectionExpensive) => {
          this.props.dispatch(ChangeNetExpensiveStatus(isConnectionExpensive));
      });
             
      Ionicons.getImageSource('ios-arrow-back', 30, '#fff').then((source) => this.setState({ backButtonImage: source }));
      Ionicons.getImageSource('md-qr-scanner', 30, '#fff').then((source) => this.setState({ rightBtnScanImage: source }));
  }

  componentWillUnmount() {
      NetInfo.removeEventListener('change',this.handleConnectionInfoChange.bind(this));
      NetInfo.isConnected.removeEventListener('change',this.handleConnectivityChange.bind(this));      
  }
  
  handleConnectionInfoChange(connectionInfo){
      var info=this.switchConnectionInfo(connectionInfo);
      this.props.dispatch(ChangeNetInfo(info));
      NetInfo.isConnectionExpensive().then((isConnectionExpensive) => {
          this.props.dispatch(ChangeNetExpensiveStatus(isConnectionExpensive));
      });
  }

  handleConnectivityChange(isConnected){
      this.props.dispatch(ChangeNetConnectStatus(isConnected));
  }

  switchConnectionInfo(connectionInfo){
      var netStatus='none';
      connectionInfo=connectionInfo.toLowerCase();
      switch (connectionInfo) {
      case 'wifi':          
          netStatus = 'wifi';
          break;
      case 'cell':           
      case 'mobile':
          netStatus = 'mobile';
          break;
      case 'unknown':           
          netStatus = 'unknown';
          break;                              
      default:
          netStatus = 'none';
          break;
      }
      return netStatus;
  }

  backAndroidHandler(){
    const scene = this.props.routes.scene;
    if(scene.name&&scene.parent){
        if(scene.name=='root'||scene.name=='main'||scene.parent=='main'||scene.name=='tab1'||scene.name=='tab2'||scene.name=='modal'){
            var datenow=Date.now();
            if (this.lastBackPressed && this.lastBackPressed + 3000 >= datenow) {
                this.props.dispatch(SceneFocus({}));
                return false;
            }
            this.lastBackPressed = datenow;
            ToastAndroid.show('再次点击退出应用',ToastAndroid.SHORT);
            return true;
        }
        Actions.pop();
        return true;
    }
    else{
        return true;
    }
  }      
  
  render() {
      return (
        this.state.backButtonImage!=null&&this.state.rightBtnScanImage!=null?
        (<View style={CommonStyles.flex1}>
        <StatusBar backgroundColor={Colors.toolbarbg} barStyle="light-content"/>
        <Router createReducer={this.reducerCreate.bind(this)} getSceneStyle={getSceneStyle} backAndroidHandler={this.backAndroidHandler}>
            <Scene key="modal" component={Modal}>
                <Scene key="root" 
                    hideNavBar={true}
                    hideTabBar={true}
                    navigationBarStyle={CommonStyles.navBarStyle} 
                    titleStyle={CommonStyles.navTitleStyle}
                    backButtonImage={this.state.backButtonImage}
                    leftButtonStyle={CommonStyles.navLeftButtonStyle} 
                    >
                    <Scene key="login" component={LoginContainer} title="登录" hideNavBar={false} panHandlers={null}/>
                    <Scene key="scanBarCode" component={ScanContainer} title="扫码" hideNavBar={false} panHandlers={null}/>
                    <Scene key="takePhoto" component={TakePhoto} title="拍照" hideNavBar={false} panHandlers={null}/>
                    <Scene key="imageUpload" component={ImageUpload} title="图片上传" hideNavBar={false} panHandlers={null}/>
                    <Scene key="main" tabs={true} default='tab1' initial={true} hideNavBar={true} tabBarStyle={CommonStyles.tabBarStyle}>
                        <Scene key="tab1"
                            component={MainContainer} 
                            title="首页"
                            getTitle={()=>AppConfig.AppName} 
                            initial={true}
                            navigationBarStyle={CommonStyles.navBarStyle} 
                            titleStyle={CommonStyles.navTitleStyle}
                            tabBarBtnStyle={CommonStyles.tabBarBtnStyle}
                            drawerImage={this.state.drawerImage}          
                            icon={TabIcon}
                            iconName='md-home'/>
                        <Scene key="tab2" 
                            component={UserCenterContainer}
                            title="我的"
                            getTitle={()=>AppConfig.AppName}
                            navigationBarStyle={CommonStyles.navBarStyle} 
                            titleStyle={CommonStyles.navTitleStyle}
                            tabBarBtnStyle={CommonStyles.tabBarBtnStyle} 
                            drawerImage={this.state.drawerImage}
                            icon={TabIcon} 
                            iconName='md-person'
                            hideNavBar={true}/>
                    </Scene>
                </Scene>                    
            </Scene>
        </Router>
        </View>):null
      );   
  }
}

export default connect(({routes}) => ({routes}))(App);


// define this based on the styles/dimensions you use
const getSceneStyle = function (/* NavigationSceneRendererProps */ props, computedProps) {
  const style = {
    flex: 1,
    backgroundColor: '#F7F7F7',
    shadowColor: null,
    shadowOffset: null,
    shadowOpacity: null,
    shadowRadius: null,
  };
  if (computedProps.isActive) {
    style.marginTop = computedProps.hideNavBar ? 0 : Platform.OS === 'ios' ? 64 : 54;
    style.marginBottom = computedProps.hideTabBar ? 0 : 50;
  }
  return style;
}